/* Filename: main.c
 * $ ps axm
 * $ ps ax -L
 * Description:
 * Last modified: humble 20200417 21:53
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include "mysem.h"

#define LEFT (30000000)
#define RIGHT (30000200)
#define THRNUM (RIGHT - LEFT +1)
#define N (4)

static mysem_t *mysem = NULL;

static void usage(void);

static void *thr_primer(void *p);

int main(int argc, char **argv)
{
    int i,err;
    pthread_t tid[THRNUM];

    if(argc != 1){
        fprintf(stderr, "argc !=1");
        usage();
        exit(1);
    }

    mysem = mysem_init(N);
    if(!mysem){
        fprintf(stderr, "mysem_init() failed\n");
        exit(1);
    }

    for(i = LEFT; i <= RIGHT; i++)
    {
        mysem_sub(mysem, 1);
        err = pthread_create(tid + (i - LEFT), NULL, thr_primer, (void *)i);
        if(err){
            fprintf(stderr, "pthread_create():%s\n", strerror(err));
            exit(1);
        }
    }

    for(i = LEFT; i <= RIGHT; i++)
    {
        pthread_join(tid[i - LEFT], NULL);
    }

    mysem_destroy(mysem);
    exit(0);
}

static void *thr_primer(void *p)
{
    int i, j, mark;

    i = (int)p;

    mark = 1;
    for(j = 2; j < i/2; j++)
    {
        if(i % j == 0){
            mark = 0;
            break;
        }
    }

    if(mark == 1){
        printf("%d is a primer\n", i);
    }

    sleep(5);

    mysem_add(mysem, 1);
    pthread_exit(NULL);
}

static void usage(void)
{
#define USAGE "Usage:\n\
  Helloworld\n"
    printf(USAGE);
}
